import pymysql
from loguru import logger
from conf.mysql_conf import mysql_conf


class HandleMysql:
    def __init__(self):
        try:
            logger.info("数据库连接开始")
            self.con = pymysql.connect(host=mysql_conf["host"],
                                       port=mysql_conf["port"],
                                       user=mysql_conf["user"],
                                       password=mysql_conf["password"],
                                       database=mysql_conf["database"],
                                       cursorclass=pymysql.cursors.DictCursor)
            logger.info("数据库连接成功")
        except:
            logger.exception("数据库连接失败, 请检查输入信息")

        # 创建游标
        self.cur = self.con.cursor()

    # 获取sql语句的查询条数
    def get_count(self, sql_query_statement):
        """

        :param sql_query_statement: 查询sql语句
        :return: 查询sql语句的条数
        """
        try:
            logger.info(f"开始执行sql语句，执行的sql语句为:{sql_query_statement}")
            count = self.cur.execute(sql_query_statement)
            logger.info("sql语句执行成功")
            return count
        except:
            logger.exception(f"sql语句执行失败, 执行的sql语句为:{sql_query_statement}")

    # 获取sql查询结果
    def get_query_sql_results(self, sql_query_statemen, size=1):
        """

        :param size: 默认size=1
                    若size = 1,则获取一条查询sql结果数据
                    若size > 1,则获取多条(多条 = size)查询sql结果数据
                    若size = -1,则获取所有的查询sql结果数据
        :return:返回查询sql结果数据
        """
        count = self.get_count(sql_query_statemen)
        if count > 0:
            if size == 1:
                sql_res = self.cur.fetchone()

            elif size > 1:
                sql_res = self.cur.fetchmany(size=size)

            elif size == -1:
                sql_res = self.cur.fetchall()

            else:
                sql_res = False
                logger.info(f"size:{size} 不符合输入要求")
            return sql_res

    def updata_mysql(self, sql_query_statemen):
        logger.info("对数据库进行更新操作")
        logger.info(f"要执行的sql语句为:{sql_query_statemen}")
        try:
            self.cur.execute(sql_query_statemen)
            self.con.commit()
            logger.info("数据库更新成功")
        except:
            self.con.rollback()
            logger.exception("数据库更新失败,执行回滚操作")
        return self

    def close_mysql(self):
        try:
            # 关闭游标连接
            self.cur.close()
            logger.info("关闭游标成功")
            # 关闭数据库连接
            self.con.close()
            logger.info("关闭数据库连接成功")
        except:
            logger.info("关闭数据库连接失败")


if __name__ == '__main__':
    hm = HandleMysql()
    sql = 'SELECT * FROM t_user WHERE phone=15012768506'
    count = hm.get_count(sql)
    print(count)
    get_data = hm.get_query_sql_results(sql, size=0)
    print(get_data)
    hm.close_mysql()
